<template>
  <el-dialog
    v-el-drag-dialog
    title="安检隐患"
    :visible.sync="visible"
    width="1200px"
    @closed="reset"
  >
    <div class="app-page">
      <aside-tree
        title="安检隐患级别"
        :tree-data="treeData"
        :mouse-button="false"
        node-key="keyVal"
        :loading="$loadingPlugin.getTreeData"
        @currentChange="currentChange"
        @refresh="getTreeData"
      />
      <div class="content">
        <div class="top-box">
          <el-button type="primary" icon="el-icon-plus" :disabled="disabled" @click="add">添加</el-button>
          <!-- <el-checkbox v-model="checked" :disabled="disabled">app端显示红色字体</el-checkbox> -->
        </div>
        <div>
          <lb-table
            ref="lbTable"
            align="center"
            element-loading-text="加载中"
            :column="column"
            :data="tableData.data"
          />
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button type="primary" @click="success(true)">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import AsideTree from '@/views/components/OrgTree'
  import { formatColumnMap } from '@/utils'
  import { checkConfigHiddenRank, openWinByCsmTypeAndPage, checkConfigInquire, checkConfigHiddenRankList, checkConfigHiddenRankSave } from '@/api'

  export default {
    name: 'hidden',
    components: {
      AsideTree
    },
    data() {
      return {
        visible: false,
        checked: false,
        disabled: false,
        current: {},
        treeData: [],
        newCradData: {},
        newTreeData: {},
        endData: {}, // 最后一项数据
        checkMapeList: [], // 随单安检项
        chooseList: [], // 安检选项
        tableData: {
          data: []
        },
        checkList1: [], // 随单安检
        checkList2: [], // 定期安检
        isExistOne: undefined,
        isExistTwo: undefined
      }
    },
    computed: {
      column: function() {
        return [
          {
            prop: 'checkType',
            label: '安检类型',
            render: (h, { row, $index }) => {
              return (
                row.isEdit ? <span>{row.checkType === 1 ? '随单安检' : row.checkType === 2 ? '定期安检' : ''}</span>
                : <el-select v-model={ row.checkType } onChange={(val) => this.change(val, row)}>
                <el-option label= { '随单安检' } value={ 1 } />
                <el-option label= { '定期安检' } value={ 2 } />
              </el-select>
              )
            }
          },
          {
            prop: 'itemName',
            label: '安检项',
            showOverflowTooltip: true,
            render: (h, { row, $index }) => {
              return (
                row.isEdit ? <span>{row.itemName ? row.itemName : row.itemId && formatColumnMap(row.checkMapeList, 'itemId', row.itemId, 'itemName') }</span>
                : <el-select v-model={row.itemId} placeholder={ '请选择' } onChange={(val) => this.changeMape(val, row)}>
                    {
                      row.checkMapeList && row.checkMapeList.map(item => {
                        return <el-option key={item.itemId} label= { item.itemName } value={ item.itemId } />
                      })
                    }
                  </el-select>
              )
            }
          },
          {
            prop: 'csmName',
            label: '安检选项',
            showOverflowTooltip: true,
            render: (h, { row, $index }) => {
              return (
                row.isEdit ? <span>{row.itemDetailNames ? row.itemDetailNames : row.itemDetailIds && formatColumnMap(row.chooseList, 'itemDetailId', row.itemDetailIds, 'itemDetailName')}</span>
                : <el-select v-model={row.itemDetailIds} multiple placeholder={ '请选择' } onChange={(val) => this.changeCsmName(val, row)}>
                    {
                       row.chooseList && row.chooseList.map(item => {
                        return <el-option key={item.itemDetailId} label= { item.itemDetailName } value={ item.itemDetailId } />
                      })
                    }
                  </el-select>
              )
            }
          },
          {
            prop: 'adviseRemark ',
            label: '建议措施',
            showOverflowTooltip: true,
            render: (h, { row, $index }) => {
              return (
                row.isEdit ? <span>{ row.adviseRemark }</span>
                : <el-input v-model={ row.adviseRemark } placeholder='请输入' clearable maxlength={ 100 }>
                  </el-input>
              )
            }
          },
          {
            prop: 'csmName',
            label: '操作',
            render: (h, { row, $index }) => {
              return (
                <div>
                  { row.isEdit === true && !this.disabled && <el-link size='mini' onClick={() => this.onEdit(row, $index)}>编辑</el-link> }
                  { row.isEdit === false && !this.disabled && <el-link size='mini' onClick={() => this.onSave(row)}>保存</el-link> }
                  { !this.disabled && <el-link size='mini' onClick={() => this.onDel(row, $index)}>删除</el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {},
    methods: {
      open(cardVal, treeVal) {
        this.newCradData = cardVal
        this.newTreeData = treeVal
        this.getTreeData(cardVal, treeVal)
        this.getopenWinByCsmTypeAndPage(cardVal, treeVal)
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      async getopenWinByCsmTypeAndPage(cardVal, treeVal) {
        const res = await openWinByCsmTypeAndPage({
          page: cardVal.id,
          csmType: cardVal.value,
          orgId: treeVal.orgId
        })
        if (res.data) {
          this.isExistOne = res.data.isExistOne
          this.isExistTwo = res.data.isExistTwo
          if (this.isExistOne === 'false' && this.isExistTwo === 'false') {
            this.disabled = true
          } else {
            this.disabled = false
          }
        }
        // console.log('res',res)
      },
      async success(val) {
        const flag = this.tableData.data.every(item => item.itemDetailIds && item.isEdit === true)
        if (flag) {
          this.tableData.data = this.tableData.data.map(item => {
            item.sp = this.checked ? 1 : 0
            return { ...item }
          })
          const list = []
          this.tableData.data.forEach(item => {
            if (item.itemDetailIds.length) {
              let newItem = {}
              item.itemDetailIds.forEach(childItem => {
                newItem = {
                  csmType: item.csmType,
                  checkType: item.checkType,
                  orgId: item.orgId,
                  orgName: item.orgName,
                  orgSNNo: item.orgSNNo,
                  warnLevel: item.warnLevel,
                  warnGrade: item.warnGrade,
                  itemId: item.itemId,
                  itemDetailId: childItem,
                  adviseRemark: item.adviseRemark
                }
                list.push(newItem)
              })
            }
          })
          console.log('保存入参', list)
          if (this.tableData.data.length) {
            const { status } = await checkConfigHiddenRankSave(list)
            if (status === 200) {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.tableData.data.map(item => {
                item.isEdit = false
              })
              await this.getHiddenApi(this.current)
              if (val) {
                this.visible = false
              }
            }
          } else { // 说明表格是空的
            if (this.endData.orgId) {
              const arr = []
              const params = {
                csmType: this.endData.csmType,
                checkType: 0,
                orgId: this.endData.orgId,
                orgName: this.endData.orgName,
                orgSNNo: this.endData.orgSNNo,
                warnLevel: this.endData.warnLevel,
                warnGrade: this.endData.warnGrade,
                itemId: 0,
                itemDetailIds: 0,
                adviseRemark: this.endData.adviseRemark
              }
              arr.push(params)
              const { status } = await checkConfigHiddenRankSave(arr)
              if (status === 200) {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                if (val) {
                  this.visible = false
                }
              }
            } else {
              if (val) {
                this.visible = false
              }
            }
          }
        } else {
          this.$message({
            message: '表格中存在未结束编辑数据',
            type: 'warning'
          })
        }
      },
      // 下层机构不可编辑安检隐患
      getDisabled(val) {
        // if (val === '001000000000000000000') {
        //   this.disabled = false
        // } else {
        //   this.disabled = true
        // }
      },
      reset() {
        this.visible = false
        this.checked = false
        this.disabled = false
        this.current = {}
        this.newCradData = {}
        this.newTreeData = {}
        this.checkMapeList = []
        this.chooseList = []
        this.tableData.data = []
        this.checkList1 = []
        this.checkList2 = []
        this.endData = {}
      },
      // 增加
      add() {
        const addData = {
          csmType: this.newCradData.value,
          checkType: '',
          orgId: this.newTreeData.orgId,
          orgName: this.newTreeData.orgName,
          isEdit: true,
          orgSNNo: this.newTreeData.orgSNNo,
          warnLevel: this.current.keyVal, // 安全级别
          warnGrade: this.current.warnGrade,
          itemId: '',
          itemDetailIds: '',
          sp: this.checked ? 1 : 0,
          adviseRemark: ''
        }
        this.tableData.data.push(addData)
        console.log('增加以后的数据', this.tableData.data)
      },
      async currentChange(current) {
        // 安全级别
        this.current = current
        // 判断是否存在某个属性
        const flag1 = this.tableData.data.every(item => !item.isEdit)
        if (flag1) {
          if (current.keyVal) {
            await this.getHiddenApi(current)
          } else {
            this.$message({
              message: '请选择安检隐患级别',
              type: 'warning'
            })
          }
        } else {
          // 判断是否有未编辑状态
          const flag2 = this.tableData.data.some(item => item.isEdit === false)
          if (flag2) {
            this.$message({
              message: '表格中存在未结束编辑数据',
              type: 'warning'
            })
          } else {
            // 判断是新数据还是老数据
            // const flag = this.tableData.data.every(item => item.itemName)
            // const flag1 = !this.tableData.data.length && !flag ? true : !!(this.tableData.data.length && flag)
            const flag1 = JSON.stringify(this.tableData.data) === JSON.stringify(this.oldTableData)
            if (flag1) {
              // 老数据
              await this.getHiddenApi(current)
            } else {
              // 新数据
              this.$confirm('切换安全隐患,是否保存当前编辑隐患级别?', '操作提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.success()
                // this.$message({
                //   message: '表格中存在未结束编辑数据',
                //   type: 'warning'
                // })
              }).catch(async() => {
                this.tableData.data = []
                // 再次请求接口
                await this.getHiddenApi(current)
              })
            }
          }
        }
      },
      async getHiddenApi(current) {
        // 随单安检
        const res = await checkConfigInquire({
          csmType: this.newCradData.value,
          checkType: 1,
          orgId: this.newTreeData.orgId,
          orgName: this.newTreeData.orgName,
          orgSNNo: this.newTreeData.orgSNNo,
          warnLevel: this.current.keyVal
        })
        this.checkList1 = res.data.filter(item => item.itemType !== -1)
        const { data } = await checkConfigHiddenRankList({
          warnLevel: current.keyVal,
          orgId: this.newTreeData.orgId,
          orgSNNo: this.newTreeData.orgSNNo,
          csmType: this.newCradData.value
        })
        // 是否可编辑
        const isEdit = true
        console.log(data)
        this.tableData.data = data.map(item => {
          item.itemId = Number(item.itemId)
          item.itemDetailIds = item.itemDetailIds.split(',')
          for (const i in item.itemDetailIds) {
            item.itemDetailIds[i] = Number(item.itemDetailIds[i])
          }
          return { ...item, isEdit }
        })
        console.log(this.tableData.data)
        if (this.tableData.data.length) {
          this.checked = this.tableData.data[0].sp === 1
        }
        this.oldTableData = JSON.parse(JSON.stringify(this.tableData.data))
        // 定期安检
        const res1 = await checkConfigInquire({
          csmType: this.newCradData.value,
          checkType: 2,
          orgId: this.newTreeData.orgId,
          orgName: this.newTreeData.orgName,
          orgSNNo: this.newTreeData.orgSNNo,
          warnLevel: this.current.keyVal
        })
        this.checkList2 = res1.data.filter(item => item.itemType !== -1)
      },
      // 安检类型
      change(val, row) {
        this.tableData.data.map(item => {
          if (item.itemId === row.itemId) {
            item.itemId = null
            item.itemDetailIds = []
          }
        })
        this.checkMapeList = []
        const checkList = val === 1 ? JSON.parse(JSON.stringify(this.checkList1)) : JSON.parse(JSON.stringify(this.checkList2))
        const hasItem = []
        this.tableData.data.forEach((item) => {
          if (item.checkType === row.checkType) {
            hasItem.push(item.itemName)
          }
        })
        const data = []
        checkList.forEach((item) => {
          let has = false
          hasItem.forEach((itemName) => {
            if (item.itemName === itemName) {
              has = true
            }
          })
          if (!has) {
            data.push(item)
          }
        })
        this.$set(row, 'checkMapeList', data)
      },
      // 编辑
      onEdit(val) {
        // 判断是否其他项正在编辑
        const obj = this.tableData.data.filter(item => item.isEdit === false)
        if (obj.length) {
          if (obj[0].checkType === '' || obj[0].itemId === '' || obj[0].itemDetailIds === '') {
            this.$message({
              message: `${obj[0].checkType === '' ? '请选择安检类型' : obj[0].itemId === '' ? '请选择安检项' : obj[0].itemDetailIds === '' ? '请选择安检选项' : ''}`,
              type: 'warning'
            })
          } else {
            if (obj[0].itemId === val.itemId) {
              val.isEdit = true
            } else {
              obj[0].isEdit = true
              val.isEdit = false
            }
          }
        } else {
          val.isEdit = false
        }
        // this.checkMapeList = val.checkType === 1 ? this.checkList1 : this.checkList2
        this.$set(val, 'checkMapeList', val.checkType === 1 ? this.checkList1 : this.checkList2)
        const arr = val.checkMapeList.filter(item => item.itemId === val.itemId)
        if (arr && arr.length) {
          this.$set(val, 'chooseList', arr[0].detailList)
        }
      },
      // 删除
      onDel(val, index) {
        if (this.tableData.data.length === 1) {
          this.endData = JSON.parse(JSON.stringify(this.tableData.data[0]))
          this.tableData.data.splice(index, 1)
        } else {
          this.tableData.data.splice(index, 1)
        }
        console.log('this.tableData.data', this.tableData.data)
      },
      // 保存
      onSave(val) {
        // 判断是否其他项正在编辑
        const obj = this.tableData.data.filter(item => item.isEdit === false)
        console.log(obj)
        if (obj.length) {
          if (obj[0].checkType === '' || obj[0].itemId === '' || obj[0].itemDetailIds.length === 0) {
            this.$message({
              message: `${obj[0].checkType === '' ? '请选择安检类型' : obj[0].itemId === '' ? '请选择安检项' : obj[0].itemDetailIds.length === 0 ? '请选择安检选项' : ''}`,
              type: 'warning'
            })
          } else {
            if (obj[0].itemId === val.itemId) {
              val.isEdit = true
            } else {
              obj[0].isEdit = true
              val.isEdit = false
            }
          }
        } else {
          val.isEdit = false
        }
        console.log('保存以后的数据', this.tableData.data)
      },
      // 安检项
      changeMape(val, row) {
        // this.$set(row, 'itemId', row.itemId)
        this.tableData.data.map(item => {
          if (item.itemDetailIds === row.itemDetailIds) {
            item.itemDetailIds = []
          }
        })
        // const arr = this.checkMapeList.filter(item => item.itemId === val)
        const arr = row.checkMapeList.filter(item => item.itemId === val)
        this.$set(row, 'chooseList', arr[0].detailList)
        this.$set(row, 'itemName', arr[0].itemName)
        // this.chooseList = arr[0].detailList
      },
      async changeCsmName(val, row) {
        // console.log('val',val)
        // console.log('row.chooseList',row.chooseList)
        const box = []
        await row.chooseList.forEach(item => {
          val.forEach(element => {
            if (item.itemDetailId === element) {
              box.push(item.itemDetailName)
            }
          })
        })
        // console.log(box)
        this.$set(row, 'itemDetailNames', box.join(','))
      },
      async getTreeData(cardVal, treeVal) {
        const res = await checkConfigHiddenRank({
          page: cardVal.id,
          csmType: cardVal.value,
          orgId: treeVal.orgId
        })
        const data = res.data.map(item => ({
          label: item.keyName,
          ...item
        }))
        this.treeData = data
        // console.log(this.treeData)
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/.el-dialog__body {
  padding-top: 0;
  padding-left: 0;
  margin-top: 0;
}
.app-page {
  display: flex;
  padding: 0;
  padding-top: 10px;
  .content {
    flex: 1;
    width: 0;
    padding: 0 10px 0 10px;
    overflow: auto;
    .top-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;
    }
  }
}
</style>
